/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iodegree;

import iodegree.lib.MyTableModel;
import iodegree.lib.CommonsLib;
import iodegree.lib.DescStats;
import iodegree.lib.Frequency;
import iodegree.lib.quadro.GenConn;
import iodegree.lib.quadro.PatternQuadro;
import java.io.File;
import java.util.ArrayList;

/**
 *
 * @author Libra
 */
public class ClusterQuadroUI extends javax.swing.JFrame {

    /**
     * Creates new form ClusterUI
     */
    public ClusterQuadroUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DataFileChooser = new javax.swing.JFileChooser();
        gluGABAGroup = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        lblOpenDatabase = new javax.swing.JLabel();
        btnQryActPatt = new javax.swing.JButton();
        btnOpenDbDefault = new javax.swing.JButton();
        btnOpenDatabase = new javax.swing.JButton();
        rdoBoth = new javax.swing.JRadioButton();
        rdoGABA = new javax.swing.JRadioButton();
        rdoGlu = new javax.swing.JRadioButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        btnGenRnd = new javax.swing.JButton();
        txtCycles = new javax.swing.JTextField();
        chkFreq = new javax.swing.JCheckBox();
        tabPanel = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        ratioPane = new javax.swing.JScrollPane();
        ratioTable = new javax.swing.JTable();
        freqPane = new javax.swing.JScrollPane();
        freqTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        simPane = new javax.swing.JScrollPane();
        simTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblOpenDatabase.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblOpenDatabase.setText("Open Database File :");

        btnQryActPatt.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnQryActPatt.setText("Query Pattern");
        btnQryActPatt.setEnabled(false);
        btnQryActPatt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQryActPattActionPerformed(evt);
            }
        });

        btnOpenDbDefault.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDbDefault.setText("Default");
        btnOpenDbDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDbDefaultActionPerformed(evt);
            }
        });

        btnOpenDatabase.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDatabase.setText("Open");
        btnOpenDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDatabaseActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoBoth);
        rdoBoth.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoBoth.setSelected(true);
        rdoBoth.setText("Both");
        rdoBoth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoBothActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoGABA);
        rdoGABA.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGABA.setText("GABA");
        rdoGABA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGABAActionPerformed(evt);
            }
        });

        gluGABAGroup.add(rdoGlu);
        rdoGlu.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        rdoGlu.setText("Glu");
        rdoGlu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdoGluActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("Random Sim :");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel8.setText("Cycles");

        btnGenRnd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnGenRnd.setText("Generate");
        btnGenRnd.setEnabled(false);
        btnGenRnd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenRndActionPerformed(evt);
            }
        });

        txtCycles.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCycles.setText("1000");
        txtCycles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCyclesActionPerformed(evt);
            }
        });

        chkFreq.setText("Frequency");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDbDefault)
                        .addGap(18, 18, 18)
                        .addComponent(rdoBoth)
                        .addGap(18, 18, 18)
                        .addComponent(rdoGlu)
                        .addGap(18, 18, 18)
                        .addComponent(rdoGABA)
                        .addGap(18, 18, 18)
                        .addComponent(btnQryActPatt))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(btnGenRnd)
                        .addGap(224, 224, 224)
                        .addComponent(chkFreq)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(lblOpenDatabase)
                    .addComponent(rdoBoth)
                    .addComponent(btnOpenDatabase)
                    .addComponent(btnOpenDbDefault)
                    .addComponent(btnQryActPatt)
                    .addComponent(rdoGlu)
                    .addComponent(rdoGABA))
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(btnGenRnd)
                    .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(chkFreq))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        ratioTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        ratioPane.setViewportView(ratioTable);

        freqTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        freqPane.setViewportView(freqTable);

        jLabel1.setText("(OBS-EXP)/EXP");

        jLabel2.setText("FREQ");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ratioPane, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(freqPane))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ratioPane, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(freqPane, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabPanel.addTab("Sums", jPanel4);

        simTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        simPane.setViewportView(simTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(simPane, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(simPane, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabPanel.addTab("Details", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tabPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tabPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOpenDbDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDbDefaultActionPerformed
        pathToFile = CommonsLib.getDefaultFile();
    }//GEN-LAST:event_btnOpenDbDefaultActionPerformed

    private void btnOpenDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDatabaseActionPerformed
        int returnVal = DataFileChooser.showOpenDialog(this);
        if (returnVal == DataFileChooser.APPROVE_OPTION) {
            pathToFile = DataFileChooser.getSelectedFile().getAbsolutePath();
//            System.out.println("File " + pathToFile + " opened.");
            btnQryActPatt.setEnabled(true);
        }
    }//GEN-LAST:event_btnOpenDatabaseActionPerformed

    private void btnQryActPattActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQryActPattActionPerformed
        getActualCluster();
        btnGenRnd.setEnabled(true);
    }//GEN-LAST:event_btnQryActPattActionPerformed

    private void txtCyclesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCyclesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCyclesActionPerformed

    private void rdoBothActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoBothActionPerformed
        type = 0;
        btnGenRnd.setEnabled(false);
    }//GEN-LAST:event_rdoBothActionPerformed

    private void rdoGluActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGluActionPerformed
        type = 1;
        btnGenRnd.setEnabled(false);

    }//GEN-LAST:event_rdoGluActionPerformed

    private void rdoGABAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdoGABAActionPerformed
        type = 2;
        btnGenRnd.setEnabled(false);

    }//GEN-LAST:event_rdoGABAActionPerformed

    private void btnGenRndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenRndActionPerformed
        getSimCluster(Integer.parseInt(txtCycles.getText()));
        fillRatioTable();
        fillFreqTable();
    }//GEN-LAST:event_btnGenRndActionPerformed

    private void getActualCluster() {
        GenConn gen=new GenConn(pathToFile);
        PatternQuadro p = new PatternQuadro();
        obs=p.clusterCount(gen.getObsPatt(),type);
    }

    private void getSimCluster(int genCycle) {
        GenConn gen=new GenConn(pathToFile);
        gen.init();
        PatternQuadro p = new PatternQuadro();
        ArrayList<int[]> countList = new ArrayList<>(100);
        for (int cy = 0; cy < genCycle; cy++) {
            countList.add(p.clusterCount(gen.genExpPatt(), type));
        }

        int[][] transposeArr = new int[countList.get(0).length][countList.size()];
        for (int i = 0; i < countList.size(); i++) {
            for (int j = 0; j < transposeArr.length; j++) {
                transposeArr[j][i] = countList.get(i)[j];
            }
        }

        exp = new double[transposeArr.length];
        sd = new double[transposeArr.length];

        for (int i = 0; i < transposeArr.length; i++) {
            DescStats stat = new DescStats(transposeArr[i]);
            exp[i] = stat.getMean();
            sd[i] = stat.getSTD();
        }
        if (chkFreq.isSelected()) {
            Frequency freq = new Frequency();
            simDataTab = freq.histogram(transposeArr);

            MyTableModel simDataM = new MyTableModel(simDataTab);
            simPane.setColumnHeaderView(null);
            simTable.setModel(simDataM);
        }
    }

    private void fillRatioTable() {
        Object[][] rtData = new Object[5][obs.length + 1];
        for (int i = 0; i < obs.length; i++) {
            rtData[0][i + 1] = new Integer(i);
            rtData[1][i + 1] = new Integer(obs[i]);
            rtData[2][i + 1] = new Double(exp[i]);
            rtData[3][i + 1] = new Double(sd[i]);
            rtData[4][i + 1] = new Double(exp[i] == 0 ? 0 : (double) (obs[i] - exp[i]) / exp[i]);
        }
        rtData[0][0] = "";
        rtData[1][0] = "Observed";
        rtData[2][0] = "Expected";
        rtData[3][0] = "Std Dev";
        rtData[4][0] = "OBS-EXP:EXP";

        MyTableModel rtoTableM = new MyTableModel(rtData);
        ratioPane.setColumnHeaderView(null);
        ratioTable.setModel(rtoTableM);
    }

    private void fillFreqTable() {
        int sum = 0;
        for (int i = 0; i < obs.length; i++) {
            sum += obs[i];
        }

        double[] obsFreq = new double[obs.length];
        double[] expFreq = new double[exp.length];

        for (int i = 0; i < exp.length; i++) {
            obsFreq[i] = (double) obs[i] / sum;
            expFreq[i] = exp[i] / sum;
        }

        int cycle = Integer.parseInt(txtCycles.getText());

        Object[][] freqData = new Object[4][obs.length + 1];
        for (int i = 0; i < obs.length; i++) {
            freqData[0][i + 1] = new Integer(i);
            freqData[1][i + 1] = new Double(obsFreq[i]);
            freqData[2][i + 1] = new Double(expFreq[i]);
            freqData[3][i + 1] = new Double((sd[i]/sum) / Math.sqrt(cycle));
        }
        freqData[0][0] = "";
        freqData[1][0] = "Observed";
        freqData[2][0] = "Expected";
        freqData[3][0] = "S.E.M";



        MyTableModel freqM = new MyTableModel(freqData);
        freqPane.setColumnHeaderView(null);
        freqTable.setModel(freqM);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClusterQuadroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClusterQuadroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClusterQuadroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClusterQuadroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClusterQuadroUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser DataFileChooser;
    private javax.swing.JButton btnGenRnd;
    private javax.swing.JButton btnOpenDatabase;
    private javax.swing.JButton btnOpenDbDefault;
    private javax.swing.JButton btnQryActPatt;
    private javax.swing.JCheckBox chkFreq;
    private javax.swing.JScrollPane freqPane;
    private transient javax.swing.JTable freqTable;
    private javax.swing.ButtonGroup gluGABAGroup;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JLabel lblOpenDatabase;
    private javax.swing.JScrollPane ratioPane;
    private transient javax.swing.JTable ratioTable;
    private javax.swing.JRadioButton rdoBoth;
    private javax.swing.JRadioButton rdoGABA;
    private javax.swing.JRadioButton rdoGlu;
    private javax.swing.JScrollPane simPane;
    private transient javax.swing.JTable simTable;
    private javax.swing.JTabbedPane tabPanel;
    private javax.swing.JTextField txtCycles;
    // End of variables declaration//GEN-END:variables
    private String pathToFile;
    private Integer[][] simDataTab;
    private int type = 0;
    private int[] obs;
    private double[] exp;
    private double[] sd;
}
